$(document).ready(function() {

    /*======update cart======*/
    $('#updCart').click(updateCart);

    //changing quote status
    $('.qstatus').change(function(){
	var urlwebsite = $('#wsurl-hidden').val();
	var qId = $(this).attr('id').replace('qstat-', '');
	var newStat = $(this).val();
	$('#ajaxmsg').ajaxStart(function(){
	    $(this).text('Changing quote status. Please wait...');
	    $(this).show();
	})
	$.ajax({
	    type : 'post',
	    url : urlwebsite+'sys/backend_quote/updatestatus/',
	    data : ({qid:qId, status:newStat}),
	    success: function(data){
		result = eval('(' + data + ')');
		if(result.error) {
		    $('#ajaxmsg').text(result.msg);
		}
		else {
		    $('#ajaxmsg').text('Quote status changed');
		    //$('#ajaxmsg').click(function(){
			//window.location.reload();
		   // })
		}
	    }
	});
    });

    //removing quote
    $('.delquote').click(function(){
	if(!confirm('Do you really want to delete this quote? This operation can not be undone.')) {
	    return false;
	}
	var urlwebsite = $('#wsurl-hidden').val();
	var qId = $(this).attr('id').replace('qdel-', '');
	$('#ajaxmsg').ajaxStart(function(){
	    $(this).text('Removing quote. Please wait...');
	    $(this).show();
	})
	$.ajax({
	    type : 'post',
	    url : urlwebsite+'sys/backend_quote/deletequote/',
	    data : ({qid:qId}),
	    success: function(data){
		result = eval('(' + data + ')');
		if(result.error) {
		    $('#ajaxmsg').text(result.msg);
		}
		else {
		    window.location.reload();
		}
	    }
	});
    });
    
//    $('#sc-products').change(function(){
//	$(this).html(replaceOnClick($(this).html()));
//    });
})

function updateCart(noReload) {
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    var quoteId = $('#quoteId-hidden').val();
    //items to be removed
    var toRemove   = [];
    //items's price to be updated
    var toUpdate   = [];
    //items's note
    var adminNotes = [];
    //items's qty
    var toUpdQty   = []

    var shipping = $('#shipping').val();
    if ($('#shipping-data').size()) {
        var shippingData = {
            firstname: $('#shipping-firstname').val(),
            lastname: $('#shipping-lastname').val(),
            email: $('#shipping-email').val(),
            address1: $('#shipping-address1').val(),
            address2: $('#shipping-address2').val(),
            city: $('#shipping-city').val(),
            state: $('#shipping-state').val(),
            zip: $('#shipping-zip').val(),
            country: $('#shipping-country').val(),
            phone: $('#shipping-phone').val()
        }
    }
    if (!/^([0-9.]{1,10})$/.test(shipping)) {
        shipping = 0;
    }

    //find all remove checkboxes wich are checked and make array of items that needs to bee removed
    var remCheckboxes = $('#usercart').find('input:checkbox:checked');
    if(remCheckboxes.length) {
	$.each(remCheckboxes, function() {
	    var tmpId = $(this).attr('id');
	    toRemove.push(tmpId.replace('chkbxtorem-', ''));
	})
    }

    //make array of items that needs to be updated
    var itemsToUpdate = $('#usercart').find('.itprice');
    if(itemsToUpdate.length) {
       $.each(itemsToUpdate, function() {
	    var tmpId = $(this).attr('id');
	    toUpdate.push(tmpId.replace('inptoupd-', '') + ',' + $(this).val());
       })
    }

    //find all qtys and make an array of them
    var itemsToUpdQty = $('#usercart').find('.itqty');
    if(itemsToUpdQty.length) {
       $.each(itemsToUpdQty, function() {
	    var itemId = $(this).attr('id').replace('inptoupdcnt-', '');
	    toUpdQty.push(itemId + ',' + $(this).val());
       })
    }

    //find all notes and make an array of them
    var notes = $('#usercart').find('.adminnote');
    if(notes.length) {
       $.each(notes, function() {
	    var itemId = $(this).attr('id').replace('adminnote-', '');
	    adminNotes.push(itemId + ',' + $(this).val());
       })
    }
    
    var disclaimer   = $('#quote-disclaimer').val();
    var intmsgtext   = $('#intmsgtext').val();
    var mailusertext = $('#mailusertext').val();
    //show message on ajax start
    //only if button 'update cart' pressed
    if ( false !== noReload) {
    $('#ajaxmsg').ajaxStart(function(){
        $('#shipping').attr('readonly','readonly');
	$(this).text('Updating cart. Please wait...');
	$(this).show();
    })
    }
    //send ajax request
    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/updatecart/',
	data : ({
            qid:cartId,
            toRemove:json_encode(toRemove),
            toUpdPrice:json_encode(toUpdate),
            toUpdQty:json_encode(toUpdQty),
            notes:json_encode(adminNotes),
            disclaimer: disclaimer,
            intMsgText: intmsgtext,
            mailUserText: mailusertext,
            shipping : shipping,
            shippingData : ($('#same-data-for-shipping').attr('checked') ? '1' : (shippingData !== undefined ? json_encode(shippingData) : '0')),
            quoteId : quoteId
        }),
	success: function(){
            //$('.shoppingeditquote').load(urlwebsite+'sys/backend_quote/edit/qid/' + quoteId);
            //do not reload page if function called from other function
            if ( false !== noReload) {
                $('#ajaxmsg').hide();
                window.location.reload();
            }
	},
        error : function() {
            $('#shipping').removeAttr('readonly');
        }
    });
}

function replaceOnClick(content) {
    //return content.replace(/Sc.addVariableProductToContent\('([0-9]+)'.*\)/g, 'addProductToCart($1)');
    return content.replace(/Sc.addVariableProductToContent\('([0-9]{1,10})', '.*'\)/g, 'addProductToCart($1)');
}

function addProductToCart(id) {
    var urlwebsite = $('#wsurl-hidden').val();
    var cartId = $('#qid-hidden').val()
    $('#ajaxmsg').ajaxStart(function(){
	$(this).text('Adding product. Please wait...');
	$(this).show();
    })
    $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/addproducttocart/',
	data : ({pid:id, cid: cartId}),
	success: function(data){
	    result = eval('(' + data + ')');
	    if(result.error) {
		$('#ajaxmsg').text(result.msg);
	    }
	    else {
                updateCart();
		window.setTimeout("window.location.reload()", 3000);
	    }
	}
    });
}

function updateQuoteData(quoteId) {
    var urlwebsite = $('#wsurl-hidden').val();
    var regEmail = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$/;
    var quoteMail = $('#qupdMail').val();
    var quoteDate = $('#qupdDate').val();
    quoteDate = quoteDate.replace(/\s+$/g, '');
    quoteDate = quoteDate.replace(/^\s+/g, '');
    var shipping = $('#shipping').val();
    if ($('#shipping-data').size()) {
        var shippingData = {
            firstname: $('#shipping-firstname').val(),
            lastname: $('#shipping-lastname').val(),
            email: $('#shipping-email').val(),
            address1: $('#shipping-address1').val(),
            address2: $('#shipping-address2').val(),
            city: $('#shipping-city').val(),
            state: $('#shipping-state').val(),
            zip: $('#shipping-zip').val(),
            country: $('#shipping-country').val(),
            phone: $('#shipping-phone').val()
        }
    }
    if (!/^([0-9.]{1,10})$/.test(shipping)) {
        shipping = 0;
    }

    if(quoteMail == '' || !quoteMail.match(regEmail) || quoteDate == '') {
	alert('Please, enter a valid data.');
	return;
    }    

   $('#ajaxmsg').ajaxStart(function(){
	$(this).text('Updating, please wait...');
	$(this).show();
   })
   $.ajax({
	type : 'post',
	url : urlwebsite+'sys/backend_quote/updatequoteoncreation/',
	data : ({
	    qid : quoteId,
	    qMail : quoteMail,
	    qDate : quoteDate,
        name : $('#cart-quote-name').val(),
        company : $('#cart-quote-company').val(),
        country : $('#cart-quote-country').val(),
        state : $('#cart-quote-state').val(),
        city : $('#cart-quote-city').val(),
        zip : $('#cart-quote-zip').val(),
        address1 : $('#cart-quote-address1').val(),
        address2 : $('#cart-quote-address2').val(),
        phone : $('#cart-quote-phone').val(),
        comments : $('#cart-quote-comments').val(),
        shipping : shipping,
        shippingData : ($('#same-data-for-shipping').attr('checked') ? '1' : (shippingData !== undefined ? json_encode(shippingData) : '0'))
	}),
	success: function(data){
	    result = eval('(' + data + ')');
	    if (result.error) {
		$('#ajaxmsg').text(result.msg);
	    } else {
		window.location.reload();
	    }
	}
    });
}

function generateQuote(emailSend)
{
    var quoteId = $('#quoteId-hidden').val();
    var urlwebsite = $('#wsurl-hidden').val();
    //get user mail text and internal message text
    var userMailText   = $('textarea#mailusertext').val();
    var intMessageText = $('textarea#intmsgtext').val();
    var disclaimer = $('#quote-disclaimer').val();
    var shipping = $('#shipping').val();
    if ($('#shipping-data').size()) {
        var shippingData = {
            firstname: $('#shipping-firstname').val(),
            lastname: $('#shipping-lastname').val(),
            email: $('#shipping-email').val(),
            address1: $('#shipping-address1').val(),
            address2: $('#shipping-address2').val(),
            city: $('#shipping-city').val(),
            state: $('#shipping-state').val(),
            zip: $('#shipping-zip').val(),
            country: $('#shipping-country').val(),
            phone: $('#shipping-phone').val()
        }
    }
    
    if (!/^([0-9.]{1,10})$/.test(shipping)) {
        shipping = 0;
    }
    //show message on ajax start
    $('#ajaxmsg').ajaxStart(function(){
        $('#shipping').attr('readonly','readonly');
        $(this).text('Generating quote. Please wait...');
        $(this).show();
    })

    updateCart(false);

    //send ajax request
    $.ajax({
        type : 'post',
        url : urlwebsite+'sys/backend_quote/generate/',
        data : ({
            qid : quoteId,
            intMessage : intMessageText,
            usrMailText : userMailText,
            disclaimer : disclaimer,
            shipping : shipping,
            shippingData : ($('#same-data-for-shipping').attr('checked') ? '1' : (shippingData !== undefined ? json_encode(shippingData) : '0')),
            emailSend: emailSend
        }),
        success: function(data){
            result = eval('(' + data + ')');
            if(result.error) {
                $('#ajaxmsg').text(result.msg);
                $('#shipping').removeAttr('readonly');
            }
            else {
                if (result.msg == 'success') {
                    $('#ajaxmsg').text('Quote generated. Mail sent to user.');
                }
                else if (result.msg == 'saved') {
                    $('#ajaxmsg').text('Quote generated and saved.');
                }
                
                //window.setTimeout("window.location.reload()", 3000);
                $('#ajaxmsg').click(function(){
                    window.location.reload();
                })
            }
        }
    });
}

function addProductForQuote()
{
    var urlWebsite = $('#wsurl-hidden').val();
    Sc.init({websiteurl : urlWebsite})
    Sc.idShoppingGroups = 'sc-groups';
    Sc.idShoppingProducts = 'sc-products';
    Sc.idShoppingBrands = 'sc-brands';
    Sc.forQuote = true;
    $.ajax({
        type : 'post',
        url : urlWebsite+'sys/backend_container/getgroupsandbrands/',
        success: function(data){
            result = eval('(' + data + ')');
            $('#sc-groups').html(result.groups);
            $('#sc-brands').html(result.brands);
            var contentReplaced =  replaceOnClick(result.products);
            $('#sc-products').html(contentReplaced);
            Sc.contentAllProducts = contentReplaced;
        }
    });
    //Sc.tabForContent();
    $('#sc-groupbrands').show();
}

function reCountTotalPrice(val)
{
    val = val.replace(/^\s+/g,'');
    val = val.replace(/\s+$/g,'');
    if (/^([0-9.]{1,10})$/.test(val)) {
        val = parseFloat(val);
        var currentTotal = parseFloat($('#current-grand-total').val());
        $('#grand-total span:first').html(currentTotal+val);
    } else {
        $('#grand-total span:first').html($('#current-grand-total').val());
    }
}